package com.tuozixuan.caffeine;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import com.github.benmanes.caffeine.cache.AsyncCache;
import com.github.benmanes.caffeine.cache.Caffeine;

public class ManualAsyncDemo {

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		
		AsyncCache<String, String> cache = Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.MINUTES).maximumSize(10_000).buildAsync();
		
		String key = "name";
		// 查找一个缓存元素， 没有查找到的时候返回null
		CompletableFuture<String> name = cache.getIfPresent(key);
		System.out.println("name:" + (name == null ? "" : name.get()));
		
		// 查找缓存元素，如果不存在，则异步生成
		name = cache.get(key, k -> {return "lisi";});
		System.out.println("name:" + name.get());
		
		// 添加或者更新一个缓存元素
		cache.put(key, name);
		
		// 移除一个缓存元素
		cache.synchronous().invalidate(key);
		
	}

}
